package com.kotlin.lib

import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlin.system.measureTimeMillis

suspend fun massive(action: suspend () -> Unit) {
    val measureTimeMillis = measureTimeMillis {
        coroutineScope {
            repeat(100) {
                launch(Dispatchers.IO) {
                    repeat(1000) {
                        println("${Thread.currentThread()}")
                        action.invoke()
                    }
                }
            }
        }
    }
    println("repeat ${100 * 1000} action in $measureTimeMillis")
}

val newSingleThreadContext = newSingleThreadContext("mainThread")

//@Volatile
var counter = 0
val lock = Mutex()
fun main() = runBlocking<Unit> {

/*    val launch = launch(Dispatchers.Default) {
        massive { counter++ }
    }*/

//    withContext(newSingleThreadContext) {
//        massive {
//            counter++
//
//        }
//    }
/*    massive {
        withContext(Dispatchers.Default) {
            counter++
        }
    }*/

    withContext(Dispatchers.Default) {
        massive { lock.withLock { counter++ } }
    }
//    launch.join()
    println("counter=$counter")
}